#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

struct complex2{
	int re1;
	int im1;
	int re2;
	int im2;	
};

void *addComplex(void *para)
{
    struct complex2 * c;
    
    c = (struct complex2*) para;
    printf("The first complex number is: %d + %di\n", (c)->re1, (c)->im1);
    printf("The second complex number is: %d + %di\n", (c)->re2, (c)->im2);
    printf("Add them: %d + %di\n", (c)->re1+(c)->re2, (c)->im1+(c)->im2);
    c->re1=c->re1+c->re2;
    c->im1=c->im1+c->im2;
    printf("return: %d + %di\n", (c)->re1, (c)->im1);
    pthread_exit((void *)c);
}



int main(int argc, char *argv[]) {
    pthread_t thread;
    pthread_attr_t attr;
    int rc;
    long t;
    void* newcomplex;
	struct complex2 complex={
		.re1 = 1,
		.im1 = 2,
		.re2 = 3,
		.im2 = 4
	};
    

    /* Initialize and set thread detached attribute */
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    printf("Main: creating thread\n");
        rc = pthread_create(&thread, &attr, addComplex, (void *) &complex);
        if (rc) {
            printf("ERROR; return code from pthread_create() is % d\n", rc);
            exit(-1);
        }


    /* Free attribute and wait for the other threads */
    pthread_attr_destroy(&attr);
    rc = pthread_join(thread, &newcomplex);
        if (rc) {
            printf("ERROR; return code from pthread_join() is % d\n", rc);
            exit(-1);
        }
        printf("Main: completed join with thread. The answer is %d + %di\n", ((struct complex2*)newcomplex)->re1, ((struct complex2*)newcomplex)->im1);
   
    

    printf("Main: program completed. Exiting.\n");
    pthread_exit(NULL);
}
